package com.c.ctgproject.base;

import android.annotation.SuppressLint;
import android.content.Context;


public abstract class BaseApplication extends MyBaseApplication
        implements BaseAppCrashHandler.CrashListener {
    @SuppressLint("StaticFieldLeak")
    private static BaseApplication sBaseApplication = null;
    protected Context mContext;
    //是否正在下载更新
    private boolean isDownloadApk = false;
    //当前角色
    private String characterName = "";

    /***获取当前角色*/
    public String getCharacterName() {
        return characterName;
    }

    public void setCharacterName(String characterName) {
        this.characterName = characterName;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        sBaseApplication = this;
        Thread.setDefaultUncaughtExceptionHandler(new BaseAppCrashHandler(this.getApplicationContext(), this));
    }

    public boolean isDownloadApk() {
        return isDownloadApk;
    }

    public void setDownloadApk(boolean downloadApk) {
        isDownloadApk = downloadApk;
    }


    public Context getContext() {
        if (mContext == null) {
            mContext = this;
        }
        return mContext;
    }


    protected abstract void onAppCrash(Context context, Thread thread, Throwable ex);

    public static BaseApplication getBaseApplication() {
        return sBaseApplication;
    }


    @Override
    public void uncaughtException(Context context, Thread thread, Throwable ex) {
        printErrorInfo(ex);
        onAppCrash(context, thread, ex);
    }

    private void printErrorInfo(Throwable ex) {
        String log = "StackTrace:\n";
        StackTraceElement[] elements = ex.getStackTrace();
        for (StackTraceElement element : elements) {
            log = log.concat(element.toString() + "\n");
        }

        Throwable theCause = ex.getCause();
        if (theCause != null) {
            log = log.concat("Cause:\n");
            log = log.concat(theCause.toString() + "\n");

            elements = theCause.getStackTrace();
            log = log.concat("Cause Stack:\n");
            for (StackTraceElement element : elements) {
                log = log.concat(element.toString() + "\n");
            }
        }
    }
}
